package net.goutalk.glcs.module.organization.service.impl;

import cn.dev33.satoken.session.SaSession;
import cn.dev33.satoken.stp.StpUtil;
import net.goutalk.glcs.common.constant.GlobalConstant;
import net.goutalk.glcs.common.utils.RedisUtil;
import net.goutalk.glcs.module.organization.entity.Department;
import net.goutalk.glcs.module.organization.entity.Post;
import net.goutalk.glcs.module.organization.entity.User;
import net.goutalk.glcs.module.organization.mapper.DepartmentMapper;
import net.goutalk.glcs.module.organization.mapper.PostMapper;
import net.goutalk.glcs.module.organization.service.IPostService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import net.goutalk.glcs.module.organization.vo.SwitchPostVo;
import net.goutalk.glcs.module.system.dto.SwitchPostDto;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 岗位 服务实现类
 * </p>
 *
 * @author tanyujie
 * @since 2022-03-02
 */
@Service
@AllArgsConstructor
public class PostServiceImpl extends ServiceImpl<PostMapper, Post> implements IPostService {

    private DepartmentMapper departmentMapper;

    private RedisUtil redisUtil;

    @Override
    public SwitchPostVo switchPost(SwitchPostDto dto) {
        SwitchPostVo result = new SwitchPostVo();

        Post post = getById(dto.getPostId());
        Department department = departmentMapper.selectById(post.getDeptId());

        result.setPostId(post.getId());
        result.setPostName(post.getName());
        result.setDepartmentId(department.getId());
        result.setDepartmentName(department.getName());

        SaSession tokenSession = StpUtil.getTokenSession();

        User loginUser = tokenSession.get(GlobalConstant.LOGIN_USER_INFO_KEY, new User());
        loginUser.setPostId(post.getId());
        loginUser.setDepartmentId(department.getId());

        tokenSession.set(GlobalConstant.LOGIN_USER_INFO_KEY, loginUser);
        tokenSession.set(GlobalConstant.LOGIN_USER_POST_INFO_KEY, post);
        tokenSession.set(GlobalConstant.LOGIN_USER_DEPT_INFO_KEY, department);

        //将登陆人所选择的身份缓存起来
        //切换身份的时候 会一起修改
        redisUtil.set(GlobalConstant.LOGIN_IDENTITY_CACHE_PREFIX + loginUser.getId(), post.getId());


        return result;
    }
}
